#include <bits/stdc++.h>

using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
    int Max = INT_MIN;
    int dfs(TreeNode *root)
    {
        if (root == nullptr)
        {
            return 0;
        }
        int leftVal = dfs(root->left);
        int rightVal = dfs(root->right);
        int ret = root->val;
        ret = max(ret, ret + leftVal);
        ret = max(ret, ret + rightVal);
        Max = max(Max, ret);
        return ret;
    }
    int maxPathSum(TreeNode *root)
    {
        dfs(root);
        return Max;
    }
};